#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

import threading

from django.db import connection

def dictfetchone(cursor):
    """将游标中的一行结果转换为字典"""
    row = cursor.fetchone()
    if row:
        columns = [col[0] for col in cursor.description]
        return dict(zip(columns, row))
    return None

# 每隔1s，异步+1，写库
def increment_counter():
    global counter
    try:
        with connection.cursor() as cursor:
            cursor.execute("""
                SELECT count FROM blindbox_stats WHERE id = 1
            """)
            product = dictfetchone(cursor)
        counter = product['count']
    except Exception as e:
        return
    counter += 1
    with connection.cursor() as cursor:
        cursor.execute("""
            UPDATE blindbox_stats SET count = %s WHERE id = 1
    """, [counter])
    # 实现定时循环执行
    threading.Timer(2.0, increment_counter).start()

def main():
    increment_counter()  # 启动定时器
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'boxuser.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
